package com.komeri.komeriapl;

import static com.komeri.komeriapl.Constants.OPEN_CAMERA_REQUEST;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow.OnDismissListener;

import com.google.zxing.Result;
import com.j256.ormlite.dao.Dao;
import com.komeri.komeriapl.Constants.BarCodeType;

/**
 * バーコードスキャン画面アクティビティ
 * @author Liu Mingjia
 */
public class BarCodeCaptureActivity extends BaseCaptureActivity {

	/** 商品詳細ページのJANコードを除いた部分のURL */
	private static final String WEB_NAME_COMMODITY = "http://www.komeri.com/disp/CKmSfSwitchGoodsPage_001.jsp?JAN_CD=";
	
	/**---<START 2014/10/10>---*/
	/**
	 * intent button
	 */
	private Button inputBtn,historyBtn,qrBtn;
	private EditText inputEditText;
	/**
	 * database options
	 */
	private DataBaseHelper dbHelper;
	private Dao<BarCodeInfo, String> barCodeInfoDao;
	private List<BarCodeInfo> infoList = null ;
	/**---<END 2014/10/10>---*/
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		setContentView(R.layout.activity_bar_code_capture);
		
		super.onCreate(savedInstanceState);
		/**---<START 2014/10/10>---*/
		init();
		/**---<END 2014/10/10>---*/
		
	}
	
	/**
	 * JANコード情報をホームページに転送する
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		
		webname = WEB_NAME_COMMODITY + result.getText();
		
		insertToDataBase(webname,result.getText());
		super.handleDecode(result, barcode);
	}
	
	/**---<START 2014/10/10>---*/
	private void init(){
		inputBtn = (Button) this.findViewById(R.id.inputBtn);
		inputBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PopupWindow pop = getInputWindow(BarCodeCaptureActivity.this) ;
				pop.showAtLocation(inputBtn, Gravity.CENTER, 0, 0);
				
			}
			
		});
		historyBtn = (Button) this.findViewById(R.id.historyBtn);
		historyBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PopupWindow pop = getHistoryWindow(BarCodeCaptureActivity.this) ;
				pop.showAtLocation(inputBtn, Gravity.CENTER, 0, 0);
			}
			
		});
		
		qrBtn = (Button) this.findViewById(R.id.qrBtn);
		qrBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				sendIntent();
			}
			
		});
		dbHelper = new DataBaseHelper(this);
		try {
			barCodeInfoDao = dbHelper.getBarCodeInfoDao();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * intent to QrCodeCaptureActivity
	 */
	private void sendIntent(){
		int sendValue = 0;
		Intent openCameraIntent = new Intent(BarCodeCaptureActivity.this, QrCodeCaptureActivity.class);
		sendValue = BarCodeType.QRCODE.ordinal();
		openCameraIntent.putExtra(BaseCaptureActivity.INTENTS_KEY_BARCODE_TYPE, sendValue);
		startActivityForResult(openCameraIntent, OPEN_CAMERA_REQUEST);
		finish();
	}
	
	/**
	 * insert barcode record
	 * @param content
	 * @param id
	 */
	private void insertToDataBase(String content,String id){
		if(content!=null&&!content.equals("")){
			String time = ""+System.currentTimeMillis();
			BarCodeInfo info = new BarCodeInfo();
			info.id = time;
			info.barcode_id = id;
			info.content = content;
			info.add_time = getStampTime(time);
			try {
				barCodeInfoDao.createOrUpdate(info);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	
	/**
	 * StampTime  format  to string
	 * @param time
	 * @return
	 */
	public static String getStampTime(String time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = null;
        if (time.equals("")) {
                return "";
        }
        sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        long loc_time = Long.valueOf(time);
        re_StrTime = sdf.format(new Date(loc_time));
        return re_StrTime;
	}
	
	
	/**
     * 2014-09-26
     * @param ct
     * @return
     */	
    public PopupWindow getInputWindow(final Context ct) {			
		View view = getLayoutInflater().inflate(R.layout.activity_input_code ,null, false);		
		Button barcodeInputBtn = (Button) view.findViewById(R.id.input_btn1);
		Button historyInputBtn = (Button) view.findViewById(R.id.input_btn2);
		Button qrInputBtn = (Button) view.findViewById(R.id.input_btn4);
		Button okInputBtn = (Button) view.findViewById(R.id.input_ok);
		inputEditText = (EditText) view.findViewById(R.id.input_text);
		
    
        final PopupWindow popupWindow = new PopupWindow(view,LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		popupWindow.setFocusable(true);		
		popupWindow.setOutsideTouchable(false);
		popupWindow.setBackgroundDrawable(new BitmapDrawable()); 
		
		barcodeInputBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
			}
			
		});
		historyInputBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PopupWindow pop = getHistoryWindow(BarCodeCaptureActivity.this) ;
				pop.showAtLocation(inputBtn, Gravity.CENTER, 0, 0);
				pop.setOnDismissListener(new OnDismissListener(){

					@Override
					public void onDismiss() {
						// TODO Auto-generated method stub
						popupWindow.dismiss();
					}
					
				});
			}
			
		});
		qrInputBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				sendIntent();
			}
			
		});
		
		okInputBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String code = inputEditText.getText().toString();
				if(code.equals("")){
					Dialog alertDialog = new AlertDialog.Builder(ct). 
			                 
			                setMessage(""+ct.getResources().getString(R.string.alert_tip)).
			                setPositiveButton(R.string.alert_button, null).
			                 
			                create(); 
			        alertDialog.show(); 
					
					return;
				}
				webname = WEB_NAME_COMMODITY + code;
				insertToDataBase(webname,code);
				Goto_Web();
				popupWindow.dismiss();
			}
			
		});
		
		
		
		return popupWindow;
	}
    
    
    /**
     * 2014-09-26
     * @param ct
     * @return
     */
    public PopupWindow getHistoryWindow(final Context ct) {			
		View view = getLayoutInflater().inflate(R.layout.activity_history ,null, false);		
		Button barcodeHistoryBtn = (Button) view.findViewById(R.id.history_btn1);
		Button inputHistoryBtn = (Button) view.findViewById(R.id.history_btn2);
		Button qrHistoryBtn = (Button) view.findViewById(R.id.history_btn4);
		ListView listView = (ListView) view.findViewById(R.id.history_listview);
		
		HistoryAdapter adapter;
		
	    try {
			infoList = barCodeInfoDao.queryBuilder().orderBy("add_time", false).query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(infoList==null){
			infoList = new ArrayList<BarCodeInfo>();
		}
		
		adapter = new HistoryAdapter(this,infoList);
		listView.setAdapter(adapter);
//	    popupwindowLinear.setRight(screenWidth/10);
//        view.getBackground().setAlpha(99);      
        final PopupWindow popupWindow = new PopupWindow(view,LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		popupWindow.setFocusable(true);		
		popupWindow.setOutsideTouchable(false);
		popupWindow.setBackgroundDrawable(new BitmapDrawable()); 
		
		barcodeHistoryBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
			}
			
		});
		qrHistoryBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				sendIntent();
			}
			
		});
		inputHistoryBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PopupWindow pop = getInputWindow(BarCodeCaptureActivity.this) ;
				pop.showAtLocation(inputBtn, Gravity.CENTER, 0, 0);
				pop.setOnDismissListener(new OnDismissListener(){

					@Override
					public void onDismiss() {
						// TODO Auto-generated method stub
						popupWindow.dismiss();
					}
					
				});
				
				
			}
			
		});
		listView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				webname = infoList.get(arg2).content;
				Goto_Web();
				
			}
			
		});

		
		return popupWindow;
	}
	
  
	/**---<END 2014/10/10>---*/
	
	
}